package com.google.code.tretris.server;

import com.google.code.tretris.common.Tetromino;
import com.google.code.tretris.common.WKC;

public class GameBoard {
	private int[] blocks = new int[WKC.BOARD_WIDTH * (WKC.BOARD_HEIGHT + 1)];
	private static int GROUND_ROW = WKC.BOARD_HEIGHT * WKC.BOARD_WIDTH;

	public GameBoard() {
		super();
		for (int n = 0; n < blocks.length; n++) {
			blocks[n] = 0;
		}
		for (int n = 0; n < WKC.BOARD_WIDTH; n++) {
			blocks[n + GROUND_ROW] = 1;
		}
	}

	public synchronized boolean canPlace(final Tetromino tetromino,
			final int xoffset, final int yoffset, final int rotation) {
		for (int y = tetromino.width - 1; y > -1; y--) {
			for (int x = 0; x < tetromino.width; x++) {
				if (tetromino.rotationmasks[rotation][x][y] != 0) {
					if (blocks[(xoffset + x)
							+ ((yoffset + y) * WKC.BOARD_WIDTH)] != 0) {
						return false;
					}
				}
			}
		}
		return true;
	}

	public synchronized void reduce(final Tetromino tetromino,
			final int xoffset, final int yoffset, final int rotation) {
		for (int x = 0; x < tetromino.width; x++) {
			for (int y = 0; y < tetromino.width; y++) {
				int[][] mask = tetromino.rotationmasks[rotation];
				if ((mask[x][y]) != 0) {
					blocks[(xoffset + x) + ((yoffset + y) * WKC.BOARD_WIDTH)] = tetromino.code;
				}
			}
		}
	}

	@Override
	public synchronized String toString() {
		String message = "[";
		for (int y = 0; y < WKC.BOARD_HEIGHT; y++) {
			message += "[";
			for (int x = 0; x < WKC.BOARD_WIDTH; x++) {
				message += blocks[x + y * WKC.BOARD_WIDTH];
			}
			message += "]";
		}
		message += "]";
		return message;
	}

	public synchronized int[] getBlocks() {
		int[] copy = new int[blocks.length];
		System.arraycopy(blocks, 0, copy, 0, copy.length);
		return copy;
	}
}
